﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FarmacieDAL;
using System.Configuration;

namespace Farmacie.Managers
{
    public class AuthenticationManager
    {
        #region Singleton

        private static AuthenticationManager instance;

        public static AuthenticationManager Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new AuthenticationManager();
                }

                return instance;
            }
        }

        #endregion

        public event EventHandler LoggedUserChanged;

        private bool mIsLoggedIn = false;
        private bool mIsAdmin = false;
        private User mUserLogged;

        public bool IsLoggedIn
        {
            get { return mIsLoggedIn; }
        }

        public bool IsAdmin
        {
            get { return mIsAdmin; }
        }

        public User UserLogged
        {
            get { return mUserLogged; }
        }

        public bool Login(string username, string password)
        {
            FarmacieEntities ctx = new FarmacieEntities(ConfigurationManager.AppSettings["connection"]);
            User currentUser = ctx.User.FirstOrDefault(x => x.Utilizator.ToLower() == username.ToLower());

            if (currentUser == null) return false;

            if (password == currentUser.Parola)
            {
                mIsLoggedIn = true;
                mIsAdmin = currentUser.IsAdmin;
                mUserLogged = currentUser;
                OnLoggedUserChanged();
                return true;
            }
            else
            {
                OnLoggedUserChanged();
                return false;
            }
        }

        public void Logout()
        {
            mIsLoggedIn = false;
            mIsAdmin = false;
            mUserLogged = null;
        }

        public void OnLoggedUserChanged()
        {
            if (LoggedUserChanged != null)
                LoggedUserChanged(this, EventArgs.Empty);
        }
    }
}
